import CacheKey from '@/utils/cache/key'

// 缓存
class Cache {
  getToken = (): string => {
    return uni.getStorageSync(CacheKey.TokenKey) // torage.getItem(CacheKey.TokenKey) || ''
  }

  setToken = (value: string) => {
    // Storage.setItem(CacheKey.TokenKey, value)
    uni.setStorageSync(CacheKey.TokenKey, value)
  }

  getRefreshToken = (): string => {
    return uni.getStorageSync(CacheKey.RefreshTokenKey) // Storage.getItem(CacheKey.RefreshTokenKey) || ''
  }

  setRefreshToken = (value: string) => {
    // Storage.setItem(CacheKey.RefreshTokenKey, value)
    uni.setStorageSync(CacheKey.RefreshTokenKey, value)
  }

  set(key: string, value: any, expire?: string) {
    let data: any = {
      expire: expire ? this.time() + expire : '',
      value
    }

    if (typeof data === 'object') {
      data = JSON.stringify(data)
    }
    try {
      uni.setStorageSync(key, data)
    } catch (e) {
      return null
    }
  }

  get(key: string) {
    try {
      const data = uni.getStorageSync(key)
      if (!data) {
        return null
      }
      const { value, expire } = JSON.parse(data)
      if (expire && expire < this.time()) {
        uni.removeStorageSync(key)
        return null
      }
      return value
    } catch (e) {
      return null
    }
  }

  remove(key: string) {
    uni.removeStorageSync(key)
  }

  clear() {
    // 清除全部缓存
    uni.clearStorageSync()
  }

  time() {
    return Math.round(new Date().getTime() / 1000)
  }
}

export default new Cache()
